$(function() {
    
    /*response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
    response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
    response.setDateHeader("Expires", 0); // Proxies. */

    
    var log = console.log;

    /***********************************************************
    * APP_MODE & APP_HISTORY is sent by query string
    * ARTICLE_MODE is overwritten to EDIT 
    * afther DB insert (article status -1)
    ***********************************************************/

    var APP_MODE = '';
    var APP_HISTORY = true;
    var ARTICLE_MODE = 'INSERT';

    // ***this goes on the global scope
    // get querystring as an array split on "&"
    var querystring;

    // declare object
    var queryObj = {};

    //for Caching
    var $content = $('#content');

    //article ID
    var artStatusId = -1;
    var mediaStatusId = -1;

    //declare flags js for creating content
    var flags = new Array();
    var FLAG = new Array();
    FLAG['EDITOR'] = false;
    FLAG['FORM'] = false;
    FLAG['MEDIA'] = false;
    FLAG['PREVIEW'] = false;
    FLAG['CATEGORY'] = false;
    FLAG['PUBLISH'] = false;
    flags['cat_tags'] = false;
    flags['conf_publish'] = false;
    flags['finish'] = false;

    edit_flag = false;
    position_flag = 0;
    //var action = 'insert';

    var catName;
    var catNameID;
    var catValue;

    var ac_index = 0;
    var publishdate; 



    if($.confirm) $.confirm.defaults = {
        text:{
            header: 'Molim potvrdite',
            ok: 'Da',
            cancel: 'Ne'
        }
    };

    /***********************************************************
    * LOAD EDITOR IF NOT INITIALIZED
    ***********************************************************/
    if(FLAG['EDITOR']==false){

        //WYSIWYG Editor
        $content.find('textarea.html').wl_Editor({
            css: base_url+'assets/css/light/editor.css'
        });
        FLAG['EDITOR']==true;
    }

    /*----------------------------------------------------------------------*/
    /* Breadcrumb
    /*----------------------------------------------------------------------*/
    
    $content.find('ul.breadcrumb').wl_Breadcrumb({
        start : 0,
        locked: false,
        disabled: true,
        onChange: function(element,id){
            switch(id){
                case 0: 

                    break;
                case 1: 

                    break;
                case 2: 

                    break;
                case 3: 

                    break;
                case 4: 

                    break;
                case 5: 

                    break;
            }
        }
    }); 

    /***********************************************************
    * Initialze application -> f1 - FORM
    ***********************************************************/
    function f1(){ 

        //log('f1:'+APP_MODE)

        if(FLAG['EDITOR']==false){

            //WYSIWYG Editor
            $content.find('textarea.html').wl_Editor({
                css: base_url+'assets/css/light/editor.css'
            });
            FLAG['EDITOR']==true;
        }

        if(FLAG['FORM']==false){            

            //The Form itself
            $content.find('form').wl_Form({
                submitButton: 'button.submit',
                resetButton: 'button.reset',
                method: 'post',
                action: null,
                ajax: true,
                serialize: false,
                parseQuery: true,
                dataType: 'text',
                status: true,
                sent: false,
                confirmSend: true,
                text: {
                    required: 'Ovo polje je obavezno',
                    valid: 'Ovo polje nije u redu',
                    password: 'Lozinka je kratka',
                    passwordmatch: 'Ovaa lozinka se ne poklapa',
                    fileinqueue: 'Postoji najmanje jedan fajl na čekanju',
                    incomplete: 'Molimo popunite formu ispravno!',
                    send: 'pošalji formu...',
                    sendagain: 'pošalji ponovo?',
                    success: 'forma poslata!',
                    error: 'greška prilikom slanja!',
                    parseerror: 'Nemogu da deserializujem query string:\n %e'
                },
                tooltip: {
                    gravity: 'nw'
                },
                onRequireError: function (element) {},
                onValidError: function (element) {},
                onPasswordError: function (element) {},
                onFileError: function (element) {},
                onBeforePrepare: function () {

                    $('#srvrserror-1').hide();

                    loader();

                    $.ajax({
                        type: "POST",
                        url: base_url+'article/f1',
                        data: {
                            uptitle: $('input[name=uptitle]').val(),
                            title: $('input[name=title]').val(),
                            text: $("#text").wysiwyg("getContent"),
                            intro: $('input[name=intro]').val(),
                            ARTICLE_MODE: ARTICLE_MODE,
                            id: artStatusId,
                        },
                        dataType: 'json',
                        success: function(data){

                            if (data.action == true){

                                artStatusId = data.id;                        

                                $('#srvrserror-1').hide(); 

                                $.modal.close();

                                ARTICLE_MODE = 'EDIT';

                                $.history.load('f2?id='+artStatusId+'&APP_MODE='+APP_MODE);

                            }else{
                                artStsudId = -1;
                                $('#srvrserror-1').html(data.msg);
                                $('#srvrserror-1').show('slow');

                                //log("Error on server:"+data.msg)

                            }


                        }
                    })

                    return false;
                },
                onBeforeSubmit: function (data) {},
                onReset: function () {},
                onComplete: function (textStatus, jqXHR) {},
                onError: function (textStatus, error, jqXHR) {},
                onSuccess: function (data, textStatus, jqXHR) {}
            });
            FLAG['FORM'] = true;
        }

        position_flag = 0;
        breadcramb_flag = 0;

        /***********************************************************
        * APP_MODE
        ***********************************************************/
        switch(APP_MODE){

            case 'INSERT':
                //log('APP_MODE is INSERT in f1')
                break;

            case 'EDIT_INSERT':
            //log('APP_MODE is EDIT_INSERT in f1');

            if(APP_HISTORY == true){
                load_started_article();     
            }

            break;

            case 'EDIT':
            //log('APP_MODE is EDIT in f1')

            if(APP_HISTORY == true){

                get_edit_article();

            }
            break;

            case 'EDIT_EDIT':
            //log('APP_MODE is EDIT_EDIT in f1')

            if(APP_HISTORY == true){

                get_edit_article();

            }

            break;
        }
    }

    /***********************************************************
    * Initialze application -> f2 - MEDIA EDITOR
    ***********************************************************/
    function f2(){ 

        //log('f2:'+APP_MODE) 

        if(FLAG['MEDIA']==false){

            /*----------------------------------------------------------------------*/
            /* Fileexplorer
            /*----------------------------------------------------------------------*/

            $content.find('div.fileexplorer').wl_Fileexplorer({
                url: base_url+'connector.php',
                toolbar: [
                ['back', 'reload', 'open', 'select', 'info', 'rename', 'copy', 'cut', 'paste', 'rm', 'mkdir', 'upload', 'duplicate', 'help']
                ],
                places: '',
                contextmenu : {
                    // Commands that can be executed for current directory
                    cwd : ['reload', 'delim', 'mkdir', 'upload', 'delim', 'paste', 'delim', 'info'], 
                    // Commands for only one selected file
                    file : ['select', 'open', 'delim', 'copy', 'cut', 'rm', 'delim', 'duplicate', 'rename'], 
                    // Coommands for group of selected files
                    group : ['copy', 'cut', 'rm', 'delim', 'info'] 
                },
                editorCallback : function(url) {
                    /*alert(url);*/

                    loader();

                    $.ajax({
                        type: "POST",
                        url: base_url+'article/f2',
                        data: {
                            id: queryObj['id'],
                            url: url
                        },
                        dataType: 'json',
                        success: function(data){

                            if (data.action == true){

                                mediaStatusId = data.id; 

                                queryObj['mediaStatusId'] = mediaStatusId;

                                $.history.load('f3?id='+queryObj['id']+'&APP_MODE='+APP_MODE);

                            }else{

                                alert("Error on server:"+data.msg)

                            }


                        }
                    })

                    return false;


                },
                closeOnEditorCallback: false,
                cutURL: 'root'
            });

            FLAG['MEDIA']=true; 

        }


        bc_next();
        position_flag = 1;
        breadcramb_flag = 1;

        /***********************************************************
        * APP_MODE
        ***********************************************************/
        switch(APP_MODE){

            case 'INSERT':
                //log('APP_MODE is INSERT in f2')
                break;

            case 'EDIT_INSERT':
            //log('APP_MODE is EDIT_INSERT in f2');

            if(APP_HISTORY == true){
                load_started_article();     
            }

            break;

            case 'EDIT':
            //log('APP_MODE is EDIT in f2')

            if(APP_HISTORY == true){

                get_edit_article();       

            }

            break;

            case 'EDIT_EDIT':
            //log('APP_MODE is EDIT_EDIT in f2')

            if(APP_HISTORY == true){

                get_edit_article();

            }

            break;
        }
    } 

    /***********************************************************
    * Initialze application -> f3 - PREVIEW
    ***********************************************************/
    function f3(){ 

        bc_next();            
        position_flag = 2;
        breadcramb_flag = 2;

        /***********************************************************
        * APP_MODE
        ***********************************************************/
        switch(APP_MODE){

            case 'INSERT':
            //log('APP_MODE is INSERT in f3')

            if(FLAG['PREVIEW']==false){

                previewArticle(queryObj['id']);
                FLAG['PREVIEW']=true;

            }

            break;

            case 'EDIT_INSERT':
            //log('APP_MODE is EDIT_INSERT in f3');

            if(APP_HISTORY == true){

                bc_next();
                load_started_article();    

            }

            break;

            case 'EDIT':
                //log('APP_MODE is EDIT in f3');

                $.modal.close();

                break;

            case 'EDIT_EDIT':
            //log('APP_MODE is EDIT_EDIT in f2')

            if(APP_HISTORY == true){

                bc_next();
                get_edit_article();

            }

            break;
        }
    } 

    /***********************************************************
    * Initialze application -> f4 - CATEGORY & TAGS
    ***********************************************************/
    function f4(){

        bc_next();            
        position_flag = 3;
        breadcramb_flag = 3;

        /***********************************************************
        * APP_MODE
        ***********************************************************/
        switch(APP_MODE){

            case 'INSERT':
            //log('APP_MODE is INSERT in f4')

            if(FLAG['CATEGORY']==false){

                get_category_tags();
                FLAG['CATEGORY']=true; 

            }

            break;

            case 'EDIT_INSERT':

            //log('APP_MODE is EDIT_INSERT in f4');

            if(APP_HISTORY == true){ 
                bc_next(); 
                bc_next(); 
                load_started_article();
                get_category_tags();
            }

            break;

            case 'EDIT':
                //log('APP_MODE is EDIT in f4')
                get_category_tags();
                break;
        }
    }

    //Initialze application -> confirm
    function f5(){ 

        bc_next();            
        position_flag = 4;
        breadcramb_flag = 4;

        /***********************************************************
        * APP_MODE
        ***********************************************************/
        switch(APP_MODE){

            case 'INSERT':
            //log('APP_MODE is INSERT in f5')

            if(FLAG['PUBLISH']==false){

                publishDate(); 
                FLAG['PUBLISH']=true;

            } 

            break;

            case 'EDIT_INSERT':
            //log('APP_MODE is EDIT_INSERT in f5');

            if(APP_HISTORY == true){

                bc_next(); 
                bc_next(); 
                bc_next(); 
                bc_next(); 
                load_started_article();

                get_category_tags();

            }

            if(FLAG['PUBLISH']==false){

                publishDate(); 
                FLAG['PUBLISH']=true;

            }     

            break; 

            case 'EDIT':
                //log('APP_MODE is EDIT in f5')  
                publishDate();
                break;
        }
    }  

    /***********************************************************
    * $.history.init
    ***********************************************************/

    $.history.init( function(hash){

        var page = hash.substring(0, 2);

        var q = hash.substring(2, hash.length);

        querystring = q.replace( '?', '' ).split( '&' );

        //log('*********************************************************** ')  

        // loop through each name-value pair and populate object
        for ( var i=0; i<querystring.length; i++ ) {

            // get name and value
            var name = querystring[i].split('=')[0];
            var value = querystring[i].split('=')[1];

            // populate object
            queryObj[name] = value;

            //log('query object:'+name+':'+value)

            if(name=='APP_MODE'){
                //log(APP_MODE)
                APP_MODE = value;
            }
        }

        /***********************************************************
        * SWITCH APP MODE
        * 3 STATES - INSERT - EDIT - EDIT_INSERT
        ***********************************************************/
        if((APP_HISTORY==true)&&(queryObj['APP_HISTORY']===undefined)&&(APP_MODE.substr(0,5)!='EDIT_')){

            APP_MODE = 'EDIT_'+APP_MODE ;

        }

        /***********************************************************
        * SWITCH ARTICLE MODE
        * 2 STATES - INSERT - EDIT
        ***********************************************************/
        if(APP_MODE.substr(0,4)=='EDIT'){

            ARTICLE_MODE = 'EDIT';

        }

        if(APP_HISTORY==true){
            if((APP_MODE=='EDIT_INSERT')||(APP_MODE=='INSERT')){
                $('h1').html('Novi članak');  
            }else if((APP_MODE=='EDIT_EDIT')||(APP_MODE=='EDIT')){
                $('h1').html('Ažuriranje članka');
            }

        }

        //queryObj['APP_MODE'] = APP_MODE;

        switch (page){

            case '':   f1(); break;  
            case 'f1': f1(); break;  
            case 'f2': f2(); break;
            case 'f3': f3(); break;
            case 'f4': f4(); break;
            case 'f5': f5(); break;

        }

        APP_HISTORY = false;

        return false;

    });

    /***********************************************************
    * LOADERS
    ***********************************************************/

    function loader()
    {
        $.modal(
        "<div><div class='animate'><img src='"+base_url+"assets/img/backgnds/loading.gif'></div><h2>Molim sačekajte...</h2></div>" , {
            closeHTML: "",
            containerCss:{
                height:70,
                width:120,
                borderColor:"#dedede"
            },
            opacity:20,
            overlayCss: {
                backgroundColor: "#000000"
            }
        });
    }

    /***********************************************************
    * Preview Article
    ***********************************************************/

    function previewArticle(id){

        $.ajax({
            type: "POST",
            url: base_url+'article/previewArticle',
            data: {
                id: id   
            },
            dataType: 'json',
            success: function(data){

                artStatusId = data.article[0].article_id;

                /*UPTITLE*/
                $('.preview .art_intro .text h2').html(data.article[0].article_uptitle);

                /*TITLE*/
                $('.preview .art_intro .text h1').html(data.article[0].article_title);

                /*MEDIA IMG VID*/
                $('.preview .art_intro .text img').attr("src", base_url+'tempatt/'+data.article[0].media_filepath);

                /*INTRO*/
                $('.preview .art_intro .text p').html(data.article[0].article_intro);

                /*ARTICLE TEXT*/
                $('.preview .art_cont .column').html(data.article[0].article_text);

                $.modal.close();

            }
        })

    }

    $('#popuni').live('click', function(){

        $('input[name=uptitle]').val("Quisque loborti"); 
        $('input[name=title]').val("Nam enim risus"); 
        $('input[name=intro]').val("Phasellus pellentesque purus in massa"); 
        $("#text").wysiwyg("insertHtml", "Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis. Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui." ); 
    }) 

    /***********************************************************
    * GET Category and Tags
    ***********************************************************/ 

    function get_category_tags(){

        if(flags['cat_tags'] == true) return false;

        $.ajax({
            type: "POST",
            url: base_url+'article/get_category_tags',
            dataType: 'json',
            success: function(data){

                if (data.action == true){

                    //log(data)
                    $.each(data.column, function(index1, value1) { 

                        if(value1.name!="tmp"){

                            /*----------------------------------------------------------------------*/
                            /* Add Columns
                            /*----------------------------------------------------------------------*/ 
                            var head = '<h4><a href="javascript:">'+value1.name+'</a></h4>';
                            $('#columns').append(head);

                            /*----------------------------------------------------------------------*/
                            /* Add Subcolumns as radio buttons
                            /*----------------------------------------------------------------------*/
                            var radios = '<table style="width:180px">'; 
                            $.each(data.subcolumn, function(index2, value2) {

                                if(value2.column_id==value1.id){

                                    //log(value1.name+':'+value2.name)                                    
                                    radios += '<tr><td style="padding:0; line-height:23px"><input type="radio" id="'+value2.name+'_radio" name="'+value1.name+'_'+value1.id+'" value="'+value2.id+'"></td><td style="padding:0; text-align:left; line-height:18px"><label for="'+value2.name+'_radio">'+value2.name+'</label></td>';                                     

                                }                                                            

                            }); 

                            radios+='</table>'

                            var div = '<div>'+radios+'</div>';                            
                            $('#columns').append(div); 


                        }

                    });
                    /*----------------------------------------------------------------------*/
                    /* Accordions
                    /*----------------------------------------------------------------------*/

                    $content.find('div.accordion').accordion({
                        collapsible:true,
                        autoHeight:false
                    });

                    /*----------------------------------------------------------------------*/
                    /* uniform plugin
                    /*----------------------------------------------------------------------*/

                    //$("select, textarea, input").not('input[type=submit], textarea.html, select[multiple]').uniform();

                    flags['cat_tags'] = true;

                    /*----------------------------------------------------------------------*/
                    /* SELECT COLUMN IF IN EDIT MODE
                    /*----------------------------------------------------------------------*/

                    if(edit_flag == true){

                        var column_name = '';

                        var cols_radios = $("div.accordion input:radio").each(function() { 
                            var strsplit = this.name.split("_"); 

                            if(strsplit[1] ==catNameID){
                                column_name = strsplit[0];
                                return false;
                            }
                        });

                        catName = column_name+"_"+catNameID;

                        $("input[name="+catName+"]").filter("[value=" + catValue + "]").attr("checked","checked");


                        var cols_acc = $("div.accordion a").each(function() { 

                            if(($(this).html()==column_name)&&(ac_index!=0)){
                                $(this).trigger('click')
                            }
                            ac_index++;
                        }); 


                        /*----------------------------------------------------------------------*/
                        /* ADD EVENT LISTENER ON CLICK 
                        /*----------------------------------------------------------------------*/

                        $("div.accordion input:radio").live('click',function(){
                            log('click')
                            //$("input[name="+catName+"]").filter("[value=" + catValue + "]").removeAttr('checked');
                            $('div.accordion').find("input:radio:checked").removeProp('checked');
                            $(this).attr("checked","checked");


                        })

                    }



                    //log(ac_index)
                }else{

                    alert("Error on server:"+data.msg)

                }


            }
        })

        return false; 
    }

    $('#conf_preview').live('click', function(){ 

        $.history.load('f4?id='+queryObj['id']+'&APP_MODE='+APP_MODE);    

    }) 

    /***********************************************************
    * SET Category and Tags
    ***********************************************************/

    $('#conf_category_tags').live('click',function(){

        var chk = $('#columns input:radio:checked');
        if(chk.attr('value')==undefined){

            $('#srvrserror-3').html('molimo odaberite kategoriju');
            $('#srvrserror-3').show('slow');

        }else{

            $('#srvrserror-1').hide();
            column_id = chk.attr('name').split("_");
            subcolumn_id = chk.attr('value');

            loader();

            $.ajax({
                type: "POST",
                url: base_url+'article/set_category_tags',
                data: {
                    id: artStatusId,
                    column_id: column_id[1],
                    subcolumn_id: subcolumn_id
                },
                dataType: 'json',
                success: function(data){

                    if (data.action == true){

                        $.modal.close();
                        flags['cat_tags'] = true;

                        $.history.load('f5?id='+queryObj['id']+'&APP_MODE='+APP_MODE);


                    }else{

                        alert("Error on server:"+data.msg)

                    }


                }
            })

            return false;

        }


    })

    /***********************************************************
    * FINISH
    ***********************************************************/

    $('#finish').live('click',function(){
        
        
        /*Get date from DATEPICKER*/
        var chosen_date = $("#redplovidbe").datepicker("getDate");        
        //show selected date before table
        var mesec = chosen_date.getMonth()+1;                             
        seldate = chosen_date.getDate() + "-" + mesec + "-" + chosen_date.getFullYear(); 
        
        publishdatetime = seldate+' '+$content.find('input.time').val();

        if(window.seldate === undefined){
            $('#srvrserror-4').html('molimo odaberite datum objave.');
            $('#srvrserror-4').show('slow'); 
            //log('error')
            return false;
        }

        id = artStatusId;

        loader();

        $.ajax({
            type: "POST",
            url: base_url+'article/finish',
            data: {
                id: id,
                app_mode: APP_MODE,
                publishdatetime: publishdatetime 
            },
            dataType: 'json',
            success: function(data){

                if (data.action == true){

                    $.modal.close();
                    flags['finish'] = true;

                    /*----------------------------------------------------------------------*/
                    /* go to preview article url 
                    /*----------------------------------------------------------------------*/
                    document.location.href = base_url + 'article/preview';


                }else{

                    alert("Error on server:"+data.msg)

                }


            }
        })

        return false;


    })

    /***********************************************************
    * Breadcamp prev - next
    ***********************************************************/

    function bc_next(to){
        $content.find('ul.breadcrumb').wl_Breadcrumb({disabled: false});
        $content.find('ul.breadcrumb').wl_Breadcrumb('next');          
        $content.find('ul.breadcrumb').wl_Breadcrumb({disabled: true});
        position_flag++; 
    }

    function bc_prev(){
        $content.find('ul.breadcrumb').wl_Breadcrumb({disabled: false});
        $content.find('ul.breadcrumb').wl_Breadcrumb('prev');
        $content.find('ul.breadcrumb').wl_Breadcrumb({disabled: true}); 
        position_flag--;
    }

    /***********************************************************
    * LOAD STARTED ARTICLE
    ***********************************************************/

    function load_started_article(){

        loader();



        $.ajax({
            type: "POST",
            url: base_url+'article/check_art_insert',
            dataType: 'json',
            success: function(data){

                if (data.action == true){

                    if (data.msg == true){

                        $.modal.close();

                        //log('load_started_article')

                        $('#dialog_confirm').click(function(){

                            $.confirm("Nastavite unos prethodnog članka?",

                            /***********************************************************
                            * load article -> FORM, MEDIA, PREVIEW, CAT & TAGS
                            ***********************************************************/

                            function(){

                                //log('load_started_article')
                                //action = 'edit';
                                artStatusId = data.article[0].article_id; 
                                $.msg("Članak učitan!",{header:'Poruka sistema'});
                                $('input[name=uptitle]').val(data.article[0].article_uptitle);
                                $('input[name=title]').val(data.article[0].article_title);
                                $('input[name=intro]').val(data.article[0].article_intro);


                                $("#breadcrumbcontent div:first").css("display", "block");
                                $('#text').wysiwyg('clear');
                                $("#text").wysiwyg("insertHtml", data.article[0].article_text);

                                if(position_flag!=0)$("#breadcrumbcontent div:first").css("display", "none");


                                if(data.article[0].media_filepath==null){

                                }else{
                                    $('#mediaeditorphoto').html('<img src="'+base_url+'tempatt/'+data.article[0].media_filepath+'" width="130px"/>')
                                }



                                $('.preview .art_intro .text h2').html(data.article[0].article_uptitle);
                                $('.preview .art_intro .text h1').html(data.article[0].article_title); 
                                $('.preview .art_intro .text img').attr("src", base_url+'tempatt/'+data.article[0].media_filepath);
                                $('.preview .art_intro .text p').html(data.article[0].article_intro);
                                $('.preview .art_cont .column').html(data.article[0].article_text);

                                //data to select column and subcolumn
                                catNameID = data.article[0].article_column_id;
                                catValue = data.article[0].article_subcolumn_id;

                                edit_flag = true;

                                //select column and subcolumn 
                                var column_name = '';

                                var cols_radios = $("div.accordion input:radio").each(function() { 
                                    var strsplit = this.name.split("_"); 

                                    if(strsplit[1] ==catNameID){
                                        column_name = strsplit[0];
                                        return false;
                                    }
                                });

                                catName = column_name+"_"+catNameID;

                                $("input[name="+catName+"]").filter("[value=" + catValue + "]").attr("checked","checked");    

                                //Open accordation
                                var cols_acc = $("div.accordion a").each(function() { 

                                    if(($(this).html()==column_name)&&(ac_index>0)){

                                        $(this).trigger('click')
                                    }
                                    ac_index++;
                                });


                                /***********************************************************
                                * SET APP_MODE
                                ***********************************************************/
                                APP_MODE = 'EDIT_INSERT';

                            },     

                            /***********************************************************
                            * delete article
                            ***********************************************************/

                            function(){
                                bc_prev();
                                bc_prev();
                                bc_prev();
                                bc_prev();
                                bc_prev();
                                $.msg("Brišem članak "+data.article[0].article_id+"!",{header:'Poruka sistema'});

                                $.ajax({
                                    type: "POST",
                                    url: base_url+'article/deleteone',
                                    data: {
                                        id: data.article[0].article_id
                                    },
                                    dataType: 'json',
                                    success: function(data){

                                        if (data.action == true){

                                            $.msg("Članak obrisan!");  

                                        }else{

                                            alert("Error on server:"+data.msg)

                                        }


                                    }
                                })
                            });
                        });
                        $('#dialog_confirm').trigger('click'); 

                    }else{

                        $.modal.close(); 

                    }


                }else{

                    alert("Error on server:"+data.msg)

                }


            }
        })
    }

    /***********************************************************
    * LOAD EDITED ARTICLE
    ***********************************************************/

    function get_edit_article(){

        loader();

        $.ajax({
            type: "POST",
            url: base_url+'article/get_edit_article',
            data:{id: queryObj['id']},
            dataType: 'json',
            success: function(data){

                if ((data.action == true)&&(data.msg == true)){

                    $.modal.close();

                    //log('load_started_article')
                    //action = 'edit';
                    artStatusId = data.article[0].article_id; 
                    $.msg("Članak učitan!",{header:'Poruka sistema'});
                    $('input[name=uptitle]').val(data.article[0].article_uptitle);
                    $('input[name=title]').val(data.article[0].article_title);
                    $('input[name=intro]').val(data.article[0].article_intro);

                    $("#breadcrumbcontent div:first").css("display", "block");
                    $('#text').wysiwyg('clear');
                    $("#text").wysiwyg("insertHtml", data.article[0].article_text);

                    if(position_flag!=0)$("#breadcrumbcontent div:first").css("display", "none");


                    if(data.article[0].media_filepath==null){

                    }else{
                        $('#mediaeditorphoto').html('<img src="'+base_url+'tempatt/'+data.article[0].media_filepath+'" width="130px"/>')
                    }



                    $('.preview .art_intro .text h2').html(data.article[0].article_uptitle);
                    $('.preview .art_intro .text h1').html(data.article[0].article_title); 
                    $('.preview .art_intro .text img').attr("src", base_url+'tempatt/'+data.article[0].media_filepath);
                    $('.preview .art_intro .text p').html(data.article[0].article_intro);
                    $('.preview .art_cont .column').html(data.article[0].article_text);

                    //data to select column and subcolumn
                    catNameID = data.article[0].article_column_id;
                    catValue = data.article[0].article_subcolumn_id;

                    edit_flag = true;

                    //select column and subcolumn 
                    var column_name = '';

                    var cols_radios = $("div.accordion input:radio").each(function() { 
                        var strsplit = this.name.split("_"); 

                        if(strsplit[1] ==catNameID){
                            column_name = strsplit[0];
                            return false;
                        }
                    });

                    catName = column_name+"_"+catNameID;

                    $("input[name="+catName+"]").filter("[value=" + catValue + "]").attr("checked","checked");    

                    //Open accordation
                    var cols_acc = $("div.accordion a").each(function() { 

                        if($(this).html()==column_name){
                            $(this).trigger('click')
                        }
                        ac_index++;
                    });

                    publishdate = data.article[0].article_datepublish;


                    /***********************************************************
                    * SET APP_MODE
                    ***********************************************************/
                    //APP_MODE = 'EDIT';                             


                }else{

                    alert("Error on server:"+data.msg)

                }


            }
        })
    }

    $('#prev_1').live('click', function(){
        bc_prev();
        bc_prev();
        $.history.load('f1?id='+queryObj['id']+'&APP_MODE='+APP_MODE);

    })

    $('#prev_2').live('click', function(){
        bc_prev();
        bc_prev();
        $.history.load('f2?id='+queryObj['id']+'&APP_MODE='+APP_MODE);

    })

    $('#prev_3').live('click', function(){
        bc_prev();
        bc_prev();
        $.history.load('f3?id='+queryObj['id']+'&APP_MODE='+APP_MODE);

    })

    $('#prev_4').live('click', function(){
        bc_prev();
        bc_prev();
        $.history.load('f4?id='+queryObj['id']+'&APP_MODE='+APP_MODE);

    })

    $('#next_2').live('click', function(){
        $.history.load('f3?id='+queryObj['id']+'&APP_MODE='+APP_MODE);

    })

    // must be 0 in production
    var testMounth = 0;

    function publishDate(){

        var currentTime = new Date()
        var month = currentTime.getMonth() + 1
        var day = currentTime.getDate() + 1
        var year = currentTime.getFullYear();


        var html = '<div id="text_cont" class="boxdatum"><h6 style="">Vrijeme poluobjave</h6><div id="vrijemepolaska"><input type="text" id="time" value="18:00" class="time"></div>'+
        '<h6 style="margin-top: 23px;">Datum objave</h6><div id="redplovidbe"><div class="gifloader"></div></div></div>';

        $("#cal").html(html);

        initializeDateComp(month + "-" + day + "-" + year); 

        $content.find('input.time').wl_Time({
            step :   30
        });       


    }

    function initializeDateComp(sDate){

        date = new Date(); 

        selMonth = 0;
        selYear = 0;

        // get the current date
        var minDate = new Date(date.getFullYear(), date.getMonth(), 1); //one day next before month
        var maxDate =  new Date(date.getFullYear(), date.getMonth() +1 +testMounth, -0); // one day before next month

        //log(minDate)

        $('#redplovidbe').html('');
        $('#main h2').html("Datum objave");

        $('#redplovidbe').datepicker( "destroy" );

        $.datepicker.setDefaults($.datepicker.regional['sr']);

        $('#redplovidbe').datepicker({
            inline: true,
            hideIfNoPrevNext: true,
            minDate: minDate,
            dateFormat: 'dd.mm.yy',
            numberOfMonths: 1,
            onSelect: function(dateStr) {

                log('DateCompDateStr:'+dateStr) 

                chosen_date = $.datepicker.parseDate('dd.mm.yy', dateStr);
                //chosen_date_timestamp = toTimestamp(chosen_date);

                //show selected date before table
                var mesec = chosen_date.getMonth()+1;

                seldate = chosen_date.getDate() + "-" + mesec + "-" + chosen_date.getFullYear();

                //log("datum date: " + seldate);
            },
            onChangeMonthYear: function(year, month, inst){

                selMonth = month;
                selYear = year;

            }
        });

        

        switch (APP_MODE){

            case 'INSERT':
                $('#redplovidbe').datepicker('setDate', new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1));
                break;

            case 'EDIT':
                var dt = new Date(publishdate * 1000);
                //log(dt)
                $('#redplovidbe').datepicker('setDate', new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()));
                break;
        }



    }

    function toTimestamp(strDate){
        var datum = Date.parse(strDate,'dd.mm.yy');
        return datum/1000;
    }

});
